package com.yuyi.config;

import java.util.Objects;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ConcurrentAccessException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.yuyi.model.KefuDO;
import com.yuyi.tool.MD5Tool;
import com.yuyi.wxt.dao.Kefu_WXT_DAO;

public class MyShiroRealm extends AuthenticatingRealm {
    
    @Autowired
    private Kefu_WXT_DAO kefuDao;   
    private final String SALT = "yuyigufen";
  
    /**
               * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String kefuNumber = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());    
        //查询用户信息
        KefuDO kefu = kefuDao.selectByKefuNumber(Integer.parseInt(kefuNumber));
        //账号不存在
        if(Objects.isNull(kefu)) {
            throw new UnknownAccountException("账号或密码不正确");
        }     
        //密码错误
        if(!Objects.equals(kefu.getKefuPassword(), MD5Tool.encrypt(kefuNumber, password))) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }   
        //账号锁定
        if(Objects.equals(kefu.getRemark(), "2")){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }  
        //账号重复登录
        if(Objects.equals(kefu.getKefuStatus(), 1)) {
            throw new ConcurrentAccessException ("账号已在线，请退出之后才能登录");
        }
        //登录成功时修改客服为在线状态
        kefuDao.updateKefu(Integer.parseInt(kefuNumber),System.currentTimeMillis());         
        return new SimpleAuthenticationInfo(kefu, password, ByteSource.Util.bytes(kefuNumber + SALT), getName());
    }
  
}
